package com.itheima.mybatis01.dao;

import com.itheima.mybatis01.bean.Teacher;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.lf5.util.Resource;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {

    public SqlSession getSqlSession() throws IOException {
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        is.close();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }

    @Test
    public void selectAll() throws IOException {
        SqlSession sqlSession = this.getSqlSession();
        List<Teacher> list = sqlSession.selectList("TeacherMapper.select");
        for (Teacher teacher : list) {
            System.out.println(teacher);
        }
        sqlSession.close();
    }

    @Test
    public void selectOne() throws IOException {
        SqlSession sqlSession = this.getSqlSession();
        Teacher teacher = sqlSession.selectOne("TeacherMapper.selectOne", 3);
        System.out.println(teacher);
        sqlSession.close();
    }

    @Test
    public void insert() throws IOException {
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        is.close();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Teacher teacher = new Teacher(null, "王皇后", 98);
        int insert = sqlSession.insert("TeacherMapper.insert", teacher);
        System.out.println(insert);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void update() throws IOException {
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.update("TeacherMapper.update", new Teacher(1, "王发放", 12));
        sqlSession.commit();
        sqlSession.close();
    }
    @Test
    public void delete() throws IOException {
        InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int delete = sqlSession.delete("TeacherMapper.delete",2);
        System.out.println(delete);
        is.close();
        sqlSession.commit();
        sqlSession.close();
    }
}
